<template>
  <div class="feedback-container">
    <div class="page-header">
      <h2>我的反馈与讨论</h2>
      <div class="header-actions">
        <el-button type="primary" @click="openFeedbackForm" class="submit-btn">提交新反馈</el-button>
        <el-input
          v-model="searchQuery"
          placeholder="搜索反馈内容"
          :prefix-icon="Search"
          class="search-input"
          clearable
        />
        <el-select v-model="typeFilter" placeholder="反馈类型" class="filter-select">
          <el-option label="全部" value="all" />
          <el-option label="社区讨论" value="community" />
          <el-option label="功能反馈" value="feature" />
          <el-option label="问题反馈" value="issue" />
        </el-select>
      </div>
    </div>

    <el-card class="feedback-card">
      <el-tabs v-model="activeTab" class="feedback-tabs">
        <el-tab-pane label="我的反馈" name="my-feedback">
          <el-table 
            :data="filteredFeedbacks" 
            style="width: 100%"
            :header-cell-style="{
              background: 'rgba(107, 155, 210, 0.1)',
              color: '#4a6fa5',
              fontWeight: '600'
            }"
          >
            <el-table-column prop="title" label="标题" width="200">
              <template #default="scope">
                <div class="feedback-title">
                  <span class="title-icon">{{ getFeedbackIcon(scope.row.type) }}</span>
                  <span>{{ scope.row.title }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="content" label="内容" />
            <el-table-column prop="createTime" label="发布时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag 
                  :type="getStatusType(scope.row.status)"
                  effect="light"
                  class="status-tag"
                >
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="收到的回复" name="replies">
          <el-table 
            :data="filteredReplies" 
            style="width: 100%"
            :header-cell-style="{
              background: 'rgba(107, 155, 210, 0.1)',
              color: '#4a6fa5',
              fontWeight: '600'
            }"
          >
            <el-table-column prop="feedbackTitle" label="原反馈标题" width="200" />
            <el-table-column prop="responseContent" label="回复内容" />
            <el-table-column prop="replyTime" label="回复时间" width="180" />
            <el-table-column prop="replier" label="回复人" width="120" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 反馈详情对话框 -->
    <el-dialog
      v-model="feedbackDialogVisible"
      title="反馈详情"
      width="60%"
      class="feedback-dialog"
    >
      <div v-if="currentFeedback" class="feedback-detail">
        <h3>{{ currentFeedback.title }}</h3>
        <div class="feedback-meta">
          <span>发布时间：{{ currentFeedback.time }}</span>
          <el-tag :type="getStatusType(currentFeedback.status)">
            {{ currentFeedback.status }}
          </el-tag>
        </div>
        <div class="feedback-content">
          {{ currentFeedback.content }}
        </div>
        <div class="feedback-replies" v-if="currentFeedback.replies && currentFeedback.replies.length">
          <h4>回复列表</h4>
          <div v-for="reply in currentFeedback.replies" :key="reply.id" class="reply-item">
            <div class="reply-header">
              <span class="replier">{{ reply.replier }}</span>
              <span class="reply-time">{{ reply.time }}</span>
            </div>
            <div class="reply-content">{{ reply.content }}</div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 提交反馈表单对话框 -->
    <el-dialog
      v-model="feedbackFormVisible"
      title="提交功能反馈"
      width="50%"
      class="feedback-form-dialog"
    >
      <el-form :model="feedbackForm" :rules="feedbackRules" ref="feedbackFormRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="feedbackForm.title" placeholder="请输入反馈标题"></el-input>
        </el-form-item>
        <el-form-item label="反馈内容" prop="content">
          <el-input
            v-model="feedbackForm.content"
            type="textarea"
            :rows="6"
            placeholder="请详细描述您的功能反馈内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="feedbackFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitFeedback">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'

// 配置axios
axios.defaults.baseURL = 'http://localhost:8080'
axios.defaults.headers.common['Content-Type'] = 'application/json'

const userStore = useUserStore()
const activeTab = ref('my-feedback')
const searchQuery = ref('')
const typeFilter = ref('all')
const feedbackDialogVisible = ref(false)
const currentFeedback = ref(null)
const feedbacks = ref([])
const replies = ref([])
const loading = ref(false)

// 提交反馈相关变量
const feedbackFormVisible = ref(false)
const feedbackFormRef = ref(null)
const feedbackForm = ref({
  title: '',
  content: '',
  feedback_type: 1 // 固定为功能反馈(1)
})

const feedbackRules = {
  title: [
    { required: true, message: '请输入反馈标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度应在2到50个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入反馈内容', trigger: 'blur' },
    { min: 5, max: 500, message: '内容长度应在5到500个字符之间', trigger: 'blur' }
  ]
}

// 打开反馈表单
const openFeedbackForm = () => {
  feedbackFormVisible.value = true
  // 重置表单
  if (feedbackFormRef.value) {
    feedbackFormRef.value.resetFields()
  }
}

// 提交反馈
const submitFeedback = async () => {
  if (!feedbackFormRef.value) return
  
  try {
    await feedbackFormRef.value.validate()
    
    // 确保用户已登录
    if (!userStore.userInfo?.userId) {
      ElMessage.error('请先登录')
      return
    }
    
    // 准备提交的数据，明确指定所有必需的字段
    const feedbackData = {
      title: feedbackForm.value.title,
      content: feedbackForm.value.content,
      userId: userStore.userInfo.userId,
      username: userStore.userInfo.username,
      feedbackType: 1, // 明确设置为1，确保不为null
      status: 0 // 初始状态为未回复
    }
    
    console.log('准备提交反馈:', feedbackData)
    
    // 调用添加反馈的方法
    await addFeedback(feedbackData)
    
    // 关闭对话框
    feedbackFormVisible.value = false
    
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 获取反馈列表
const fetchFeedbacks = async () => {
  try {
    loading.value = true
    console.log('开始获取反馈列表，用户信息:', userStore.userInfo)
    
    if (!userStore.userInfo?.userId) {
      console.error('用户信息不存在')
      ElMessage.error('请先登录')
      return
    }

    // 使用新的接口获取反馈列表
    const response = await axios.get(`/feedback-vo/list/byuser/${userStore.userInfo.userId}`)
    console.log('获取到的反馈列表数据:', response)

    if (response.data && Array.isArray(response.data)) {
      console.log('获取到的反馈列表数据:', response.data)
      // 格式化时间
      feedbacks.value = response.data.map(feedback => ({
        ...feedback,
        time: formatDate(feedback.createTime) // 使用createTime字段
      }))
      
      // 获取反馈的回复
      await fetchReplies()
    } else {
      console.error('返回的数据格式不正确:', response.data)
      feedbacks.value = []
      ElMessage.warning('暂无反馈数据')
    }
  } catch (error) {
    console.error('获取反馈列表失败，错误详情:', error)
    feedbacks.value = []
    ElMessage.error(error.response?.data?.message || '获取反馈列表失败')
  } finally {
    loading.value = false
  }
}

// 获取反馈详情
const fetchFeedbackDetail = async (id) => {
  try {
    console.log('开始获取反馈详情，ID:', id)
    // 使用新的接口获取反馈详情
    const response = await axios.get(`/feedback-vo/detail/${id}`)
    
    if (response.data) {
      console.log('获取到的反馈详情:', response.data)
      currentFeedback.value = {
        ...response.data,
        time: formatDate(response.data.createTime) // 格式化创建时间
      }
      feedbackDialogVisible.value = true
    } else {
      throw new Error('未获取到反馈详情')
    }
  } catch (error) {
    console.error('获取反馈详情失败，错误详情:', error)
    ElMessage.error(error.response?.data?.message || '获取反馈详情失败')
  }
}

// 获取反馈回复
const fetchReplies = async () => {
  try {
    if (!userStore.userInfo?.userId) {
      console.error('用户信息不存在')
      return
    }
    
    // 获取用户的所有反馈ID
    const feedbackIds = feedbacks.value.map(feedback => feedback.feedbackId).filter(id => id !== undefined && id !== null)
    
    if (feedbackIds.length === 0) {
      console.log('用户没有反馈或反馈ID无效，无需获取回复')
      replies.value = []
      return
    }
    
    // 为每个反馈获取回复
    const allReplies = []
    
    for (const feedbackId of feedbackIds) {
      try {
        if (!feedbackId) {
          console.log('跳过无效的反馈ID')
          continue
        }
        
        // 使用Admin_Feedbackresponse_Controller的接口获取回复
        const response = await axios.get(`/feedback_responses/feedback/${feedbackId}`, {
          params: { page: 1, pageSize: 100 } // 获取所有回复
        })
        
        if (response.data && Array.isArray(response.data)) {
          // 将回复添加到列表中，并添加对应的反馈标题
          const feedbackInfo = feedbacks.value.find(f => (f.feedbackId || f.id) === feedbackId)
          const formattedReplies = response.data.map(reply => ({
            ...reply,
            feedbackId: feedbackId,
            feedbackTitle: feedbackInfo ? feedbackInfo.title : `反馈#${feedbackId}`,
            replyTime: formatDate(reply.response_time || reply.createTime),
            replyContent: reply.responseContent,
            replier: reply.admin_name || '管理员'
          }))
          
          allReplies.push(...formattedReplies)
        }
      } catch (error) {
        console.error(`获取反馈ID ${feedbackId} 的回复失败:`, error)
      }
    }
    
    console.log('获取到的所有回复:', allReplies)
    replies.value = allReplies
  } catch (error) {
    console.error('获取回复失败:', error)
    replies.value = []
  }
}

// 添加新反馈
const addFeedback = async (feedback) => {
  try {
    if (!userStore.userInfo?.userId) {
      ElMessage.error('请先登录')
      return
    }

    console.log('开始添加新反馈，用户信息:', userStore.userInfo)
    console.log('反馈数据:', feedback)
    
    // 明确指定所有必需的字段，确保feedbackType不为null
    const feedbackData = {
      title: feedback.title,
      content: feedback.content,
      userId: userStore.userInfo.userId,
      username: userStore.userInfo.username,
      feedbackType: 1, // 明确设置为1，确保不为null
      status: 0
    }
    
    console.log('提交到后端的数据:', feedbackData)
    
    const response = await axios.post('/feedbacks/add', feedbackData)
    
    console.log('添加反馈响应:', response.data)
    if (response.data > 0) {
      ElMessage.success('功能反馈提交成功')
      await fetchFeedbacks()
    }
  } catch (error) {
    console.error('添加反馈失败，错误详情:', error)
    ElMessage.error(error.response?.data?.message || '反馈提交失败')
  }
}

// 更新反馈
const updateFeedback = async (feedback) => {
  try {
    const response = await axios.put('/feedbacks/update', feedback)
    if (response.data > 0) {
      ElMessage.success('反馈更新成功')
      fetchFeedbacks() // 刷新列表
    }
  } catch (error) {
    ElMessage.error('反馈更新失败')
    console.error('反馈更新失败:', error)
  }
}

// 删除反馈
const deleteFeedback = async (id) => {
  try {
    const response = await axios.delete(`/feedbacks/delete/${id}`)
    if (response.data > 0) {
      ElMessage.success('反馈删除成功')
      fetchFeedbacks() // 刷新列表
    }
  } catch (error) {
    ElMessage.error('反馈删除失败')
    console.error('反馈删除失败:', error)
  }
}

// 修改现有的视图方法
const viewFeedbackDetail = (id) => {
  fetchFeedbackDetail(id)
}

const viewReplyDetail = (id) => {
  fetchFeedbackDetail(id)
}

// 在组件挂载时获取数据
onMounted(async () => {
  console.log('组件挂载，当前用户信息:', userStore.userInfo)
  if (userStore.userInfo?.userId) {
    await fetchFeedbacks()
  } else {
    ElMessage.warning('请先登录')
  }
})

const filteredFeedbacks = computed(() => {
  if (!Array.isArray(feedbacks.value)) {
    console.warn('feedbacks不是数组:', feedbacks.value)
    return []
  }

  console.log('过滤前的反馈列表:', feedbacks.value)
  console.log('当前搜索关键词:', searchQuery.value)
  console.log('当前类型过滤:', typeFilter.value)
  
  const filtered = feedbacks.value.filter(feedback => {
    if (!feedback) return false
    
    const matchesSearch = feedback.content?.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
                         feedback.title?.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesType = typeFilter.value === 'all' || feedback.type === typeFilter.value
    return matchesSearch && matchesType
  })
  
  console.log('过滤后的反馈列表:', filtered)
  return filtered
})

const filteredReplies = computed(() => {
  return replies.value.filter(reply => {
    return reply.feedbackTitle?.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
           reply.replyContent?.toLowerCase().includes(searchQuery.value.toLowerCase())
  })
})

const getFeedbackIcon = (type) => {
  const icons = {
    'community': '💬',
    'feature': '💡',
    'issue': '⚠️'
  }
  return icons[type] || '📝'
}

const getStatusType = (status) => {
  const types = {
    '1': 'success',
    '0': 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    '1': '已回复',
    '0': '待回复'
  }
  return texts[status] || '未知状态'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知时间';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}
</script>

<style scoped>
.feedback-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  margin-top: 0 !important;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-card__body) {
  padding: 20px !important;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 24px;
}

.page-header h2 {
  color: #4a6fa5;
  font-size: 1.5rem;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-input {
  width: 240px;
}

.filter-select {
  width: 120px;
}

.submit-btn {
  background: linear-gradient(135deg, #6b9bd2, #4a6fa5);
  border: none;
  padding: 8px 16px;
  font-weight: 600;
}

.feedback-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(107, 155, 210, 0.1);
  box-shadow: 0 8px 32px rgba(107, 155, 210, 0.1);
}

.feedback-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4a6fa5;
}

.title-icon {
  font-size: 16px;
}

.status-tag {
  border-radius: 12px;
  padding: 2px 8px;
}

.feedback-detail {
  padding: 20px;
}

.feedback-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 0;
  color: #666;
}

.feedback-content {
  margin: 20px 0;
  line-height: 1.6;
  color: #333;
}

.feedback-replies {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding: 20px;
}

.reply-item {
  margin: 16px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #666;
}

.reply-content {
  color: #333;
  line-height: 1.5;
}

:deep(.el-table) {
  --el-table-border-color: rgba(107, 155, 210, 0.1);
  --el-table-header-bg-color: rgba(107, 155, 210, 0.1);
}

:deep(.el-table th) {
  font-weight: 600;
  color: #4a6fa5;
}

:deep(.el-table td) {
  color: #5a7ba8;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #6b9bd2, #8bb6e8);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a8bc1, #7aa5d7);
  transform: translateY(-1px);
}

:deep(.el-tabs__item) {
  color: #4a6fa5;
}

:deep(.el-tabs__item.is-active) {
  color: #6b9bd2;
}

/* 表单样式 */
.feedback-form-dialog :deep(.el-form-item__label) {
  font-weight: 600;
  color: #4a6fa5;
}

.feedback-form-dialog :deep(.el-textarea__inner) {
  resize: none;
  border-color: #dcdfe6;
}

.feedback-form-dialog :deep(.el-textarea__inner:focus),
.feedback-form-dialog :deep(.el-input__inner:focus) {
  border-color: #6b9bd2;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 0 16px;
  }

  .header-actions {
    flex-direction: column;
  }

  .search-input,
  .filter-select {
    width: 100%;
  }
}
</style> 